package cn.edu.lingnan.controllerV1;

import cn.edu.lingnan.constant;
import cn.edu.lingnan.service.RoleManageService;
import cn.edu.lingnan.user.pojos.Menu;
import cn.edu.lingnan.user.dtos.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/roleManage")
public class RoleManageController {

    @Autowired
    private RoleManageService roleManageService;

    // 查询教师角色的菜单权限（返回树形结构）
    @GetMapping("/getMenusByRoleId")
    public Result<List<Menu>> getMenusByRoleId(@RequestParam int roleId) {
        List<Menu> menus = roleManageService.getMenusByRoleId(roleId);
        List<Menu> menuTree = roleManageService.buildMenuTree(menus);
        return Result.success(menuTree);
    }

    // 查询所有菜单权限（返回树形结构）
    @GetMapping("/getAllMenus")
    public Result<List<Menu>> getAllMenus() {
        List<Menu> menus = roleManageService.getAllMenus();
        List<Menu> menuTree = roleManageService.buildMenuTree(menus);
        return Result.success(menuTree);
    }

    // 添加教师角色的菜单权限
    @PostMapping("/addMenuToRole")
    public Result<String> addMenuToRole(@RequestParam int roleId, @RequestParam int menuId) {
        roleManageService.addMenuToRoleWithParentCheck(roleId, menuId);
        return Result.success(constant.ADD_TEACHER_MENU_SUCCESS);
    }

    // 删除教师角色的菜单权限
    @DeleteMapping("/removeMenuFromRole")
    public Result<String> removeMenuFromRole(@RequestParam int roleId, @RequestParam int menuId) {
        roleManageService.removeMenuAndChildrenFromRole(roleId, menuId);
        return Result.success(constant.REMOVE_TEACHER_MENU_SUCCESS);
    }

    // 删除教师角色的菜单权限（带密码验证）
    @DeleteMapping("/removeMenuFromRoleWithPassword")
    public Result<String> removeMenuFromRoleWithPassword(
            @RequestHeader("Authorization") String jwt, // 从请求头中获取 JWT
            @RequestParam int roleId, // 从前端传入 roleId
            @RequestParam int menuId,
            @RequestParam String password
    ) {
        jwt = jwt.replace("Bearer ", ""); // 去掉 "Bearer " 前缀
        roleManageService.removeMenuAndChildrenFromRoleWithPassword(jwt, roleId, menuId, password);
        return Result.success(constant.REMOVE_TEACHER_MENU_SUCCESS);
    }
}